#include "tcpserver.h"
#include <QDebug>

TcpServer::TcpServer(QObject *parent)
    : QTcpServer(parent), m_running(false)
{
    m_clientManager = new ClientManager(this);
    m_threadPool = new ThreadPool(10, this);
    
    connect(m_clientManager, &ClientManager::clientConnected,
            this, &TcpServer::onClientConnected);
    connect(m_clientManager, &ClientManager::clientDisconnected,
            this, &TcpServer::onClientDisconnected);
    connect(m_clientManager, &ClientManager::messageReceived,
            this, &TcpServer::onMessageReceived);
    connect(m_clientManager, &ClientManager::errorOccurred,
            this, &TcpServer::onErrorOccurred);
}

TcpServer::~TcpServer() {
    stopServer();
}

bool TcpServer::startServer(const QHostAddress &address, quint16 port) {
    if (m_running) {
        QTextStream(stdout) << "Server is already running"<<"\n";
        return false;
    }

    if (!listen(address, port)) {
        QTextStream(stdout) << "Failed to start server:" << errorString()<<"\n";
        emit serverError(errorString());
        return false;
    }

    m_running = true;
    QTextStream(stdout) << "Server started on " << address.toString() << ":" << port<<"\n";
    return true;
}

void TcpServer::stopServer() {
    if (m_running) {
        close();
        m_running = false;
        QTextStream(stdout) << "Server stopped"<<"\n";
    }
}

int TcpServer::clientCount() const {
    return m_clientManager->clientCount();
}

QList<qintptr> TcpServer::clientList() const {
    return m_clientManager->clientList();
}

void TcpServer::broadcastMessage(const QString &message) {
    m_clientManager->broadcastMessage(message);
}

void TcpServer::sendToClient(qintptr descriptor, const QString &message) {
    m_clientManager->sendToClient(descriptor, message);
}

void TcpServer::incomingConnection(qintptr socketDescriptor) {
    QTextStream(stdout) << "New incoming connection:" << socketDescriptor<<"\n";
    m_clientManager->addClient(socketDescriptor);
}

void TcpServer::onClientConnected(qintptr descriptor, const QString &info) {
    emit clientConnected(descriptor, info);
}

void TcpServer::onClientDisconnected(qintptr descriptor) {
    emit clientDisconnected(descriptor);
}

void TcpServer::onMessageReceived(qintptr descriptor, const QString &message) {
    emit messageReceived(descriptor, message);
}

void TcpServer::onErrorOccurred(qintptr descriptor, const QString &error) {
    QTextStream(stdout) << "Client error:" << descriptor << error<<"\n";
    emit serverError(QString("Client %1 error: %2").arg(descriptor).arg(error));
}
